import * as XLSX from "xlsx";
import {computed, onMounted, onUnmounted, shallowRef} from "vue";

/**
 * @param options {import('xlsx').Sheet2JSONOpts | {startRow: number}}
 * @returns {Promise<Object>}
 */
export function readExcel(options = {}) {

	/**
	 *
	 * @param sheet {import('xlsx').WorkSheet}
	 */
	function readRows(sheet) {
		/**
		 * @type {Array<Array<any>>}
		 */
		return XLSX.utils.sheet_to_json(sheet, options).slice(options.startRow - 1);
	}

	return selectFiles(false, '.xls,.xlsx')
		.then(([file]) => new Promise((resolve, reject) => {
			const fileReader = new FileReader();
			fileReader.onload = (e) => {
				const workBook = XLSX.read(e.target.result, { type: 'buffer' });
				const data = []
				for (let sheetsKey in workBook.Sheets) {
					data.push(...readRows(workBook.Sheets[sheetsKey]))
				}
				resolve(data)
			}
			fileReader.onerror = reject
			fileReader.readAsArrayBuffer(file)
		}))
}

/**
 *
 * @param multi
 * @param accept
 * @returns {Promise<FileList>}
 */
export function selectFiles(multi = false, accept = "*") {
	return new Promise((resolve, reject) => {
		const input = document.createElement('input');
		input.type = 'file'
		input.multiple = multi
		input.accept = accept
		input.onchange = () => {
			resolve(input.files)
		}
		input.oncancel = () => {
			reject()
		}
		input.click()
	})
}


/**
 *
 * @param antTable {import('vue').ShallowRef}
 */
export function useAntTableScroll(antTable) {
	const key = shallowRef(0)
	const scroll = computed(() => {
		const k = key.value
		console.debug(k)
		return {
			x: 'max-content',
			y: antTable.value ? antTable.value.$el.querySelector('.ant-table').getBoundingClientRect().height - 100 : 0
		}
	})

	const listener = () => {
		key.value++
	};
	onMounted(() => {
		window.addEventListener('resize', listener)
	})

	onUnmounted(() => {
		window.addEventListener('resize', listener)
	})

	return scroll
}
